from django.shortcuts import render,HttpResponse,redirect
from app01.utils.bootstrapmodel import BootStrapForm
from django import forms
from app01.utils.encrypt import md5
from app01.models import Adminuser
from app01.utils.code import check_code
#BytesIO写在内存里的文件
from io import BytesIO
# class LoginForm(forms.Form):
class LoginForm(BootStrapForm):
    username=forms.CharField(
        label="用户名",
        # widget=forms.TextInput(attrs={'class':'form-control'})
        widget=forms.TextInput,
        required=True
    )
    password=forms.CharField(
        label='密码',
        # widget=forms.PasswordInput(attrs={'class':'form-control'})
        widget=forms.PasswordInput(render_value=True),
        required=True
    )
    code= forms.CharField(
        label='验证码',
        # widget=forms.PasswordInput(attrs={'class':'form-control'})
        widget=forms.TextInput,
        required=True
    )
    def clean_password(self):
        pwd=self.cleaned_data.get('password')
        return md5(pwd)
    # def __init__(self,*args,**kwargs):
    #     super().__init__(*args,**kwargs)
    #     for name,field in self.fields.items():
    #         if field.widget.attrs:
    #             field.widget.attrs['class']='form-control'
    #             field.widget.attrs['placeholder']=field.label
    #         else:
    #             field.widget.attrs={
    #                 'class':'form-control',
    #                 'placeholder':field.label
    #             }

# class LoginModelForm(forms.ModelForm):
#     class Meta:
#         model=models.Admin
#         fields=['username','password']

def login(request):
    '''登录'''
    if request.method=='GET':
        form=LoginForm()
        return render(request,'login.html',{'form':form})

    form=LoginForm(data=request.POST)
    if form.is_valid():
        # print(form)
        #验证成功，获取到用户名和密码{'username': 'kate1', 'password': '123456','code':xxx}
        # print('*'*10)
        #验证码的校验
        user_input_code=form.cleaned_data.pop('code')
        image_code=request.session.get('image_code','')#获取用户输入的验证码，如果没有返回空
        # print(f'image_code is {image_code}')
        # print(f'user_input_code is{user_input_code}')
        if image_code.upper()!=user_input_code.upper():
            form.add_error("code",'验证码错误')
            return render(request, 'login.html', {'form': form})


        # print(form.cleaned_data)
        #去数据库校验用户名和密码是否正确,获取用户对象，如果用户名和密码不存在返回为空
        # admin_obj=Adminuser.objects.filter(username=form.cleaned_data['username'],password=form.cleaned_data['password']).first()
        admin_obj=Adminuser.objects.filter(**form.cleaned_data).first()
        # print(admin_obj)
        if not admin_obj:
            #在密码下面主动添加错误
            # form.add_error('username','用户名或密码错误')
            form.add_error('password','用户名或密码错误')
            return render(request,'login.html',{'form':form})
        # 用户名和密码输入正确
        #网站生成随机字符串；写到用户浏览器的cookie中，在写入到session中
        request.session['info']={'id':admin_obj.id,'name':admin_obj.username}
        #session可以保存7天
        request.session.set_expiry(60*60*24*7)#设置登录保持7天时长
        return redirect('/admin/list/')
        # return HttpResponse("提交成功")

    return render(request,'login.html',{'form':form})

def image_code(request):
    """生成图片验证码"""
    img,code_string= check_code()
    print(f'code_string is {code_string}')
    #写入到自己的session中（以便于后续获取验证码再进行校验）
    request.session['image_code']=code_string
    #给session设置60s超时
    request.session.set_expiry(60)#7天免登录

    stream = BytesIO()
    img.save(stream, 'png')
    if not img:
        raise ValueError("Image object is not valid")

    return HttpResponse(stream.getvalue())
def logout(request):
    '''注销'''
    request.session.clear()
    return redirect('/login/')